<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Auth;
use app\common\zhengshu\WechatPayTransfer;
use think\Db;


/**
 * 示例接口
 */
class Zhuchang extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['faxinTotal','yiFaxinList','weiFaxinList'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['tixian','zhangdanList','projectZhangdanList','faxinTotal','weiFaxinList','yiFaxinList','myUserList','projectQingjiaList','saoyisao','yaoqing','userAlreadyList','addProject','projectList','qingjiacheck','qingjiacheckGongsi','faxin','yijianfaxin','faHongbao','askAnswer'];


    /**
     * 添加请假
     * @ApiMethod (POST)
     * @param string $type
     * @param string $reason
     * @param string $startime
     * @param string $endtime
     * @param string $file
     */
    public function addProject()
    {
        $faxintype = $this->request->post('faxintype');
        $faxintian = $this->request->post('faxintian');
        $projectname = $this->request->post('projectname');
        $cid = $this->auth->id;//公司id，用user，类型公司的用户。
        $company = $this->request->post('company');
        $riqi = $this->request->post('riqi');
        $riqiend = $this->request->post('riqiend');
        $gongzuoriqi = $this->request->post('gongzuoriqi');
        $gongzuoshijianM = $this->request->post('gongzuoshijianM');
        $gongzuoshijianA = $this->request->post('gongzuoshijianA');
        $dakadizhi = $this->request->post('dakadizhi');
        $longitude = $this->request->post('longitude');
        $latitude = $this->request->post('latitude');
        $yaxin = $this->request->post('yaxin');
        $fabuzheName = $this->request->post('fabuzheName');
        $fabuzheZhiwei = $this->request->post('fabuzheZhiwei');
        $salary = $this->request->post('salary');
        if (!$projectname ) {
            $this->error(__('Invalid parameters'));
        }
        $data = [
            'cUid' => $this->auth->id,//驻场端用户
            'faxintype' => $faxintype,
            'faxintian' => $faxintian,
            'projectname' => $projectname,
            'cid' => $cid,
            'company' => $company,
            'riqi' => $riqi,
            'riqiend' => $riqiend,
            'gongzuoriqi' => $gongzuoriqi,
            'gongzuoshijianM'=>$gongzuoshijianM,
            'gongzuoshijianA'=>$gongzuoshijianA,
            'dakadizhi'=>$dakadizhi,
            'longitude'=>$longitude,
            'latitude'=>$latitude,
            'yaxin'=>$yaxin,
            'fabuzheName'=>$fabuzheName,
            'fabuzheZhiwei'=>$fabuzheZhiwei,
            'salary'=>$salary,
            'createtime'=>time(),
            'yaoqingcode'=>str_pad(mt_rand(0, 999999), 6, "0", STR_PAD_BOTH)
        ];

        Db::name('gongzuo_project')->insert($data);

        $this->success('创建成功', ['action' => 'addProject']);
    }

    /**
     * 我的项目列表
     * @ApiMethod (GET)
     */
    public function projectList()
    {
        $page =    $this->request->get('page');
        $pageSize = $this->request->get('pageSize');
        $faxintype = $this->request->get('faxintype');
        $pName = $this->request->get('pName');

        $where = ['cUid' => $this->auth->id ];
        if(!empty($faxintype)){
            $where['faxintype'] = $faxintype;
        }
        if(!empty($pName)){
            $where['projectname'] =[ 'like', '%' . $pName . '%'];
        }
        $total = Db::name('gongzuo_project')->where($where)->count();
        $pagesNum  = ceil($total/$pageSize);
        $list  = Db::name('gongzuo_project')->where($where)->order(['id'=>'desc'])->limit(($page-1)*$pageSize, $pageSize)->select();
        //$thisUserObj = new User();
        if(!empty($list)){
            foreach ($list as $Item =>$value){
                $cUser  = Db::name('user')->where(['id'=>$value['cUid']])->find();
                //$url  = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http";
                //$url .= "://" . $_SERVER['HTTP_HOST'];
                //$url .= $_SERVER['REQUEST_URI'];
                $thisAvatar = $cUser['avatar'];
                $list[$Item]['fubuzheTouxiang'] = $thisAvatar;
                $list[$Item]['fubuzheMobile'] = $cUser['mobile'];
                //统计这个项目的人数
                $projectNums = Db::name('gongzuoshenqing')->where(['tid'=>$value['id']])->count();
                $list[$Item]['projectNums'] = $projectNums;
                $list[$Item]['createtime'] = date('Y-m-d H:i:s',$value['createtime']);

            }
        }
        //echo  Db::name('gongzuo_project')->getLastSql();
        $data  =array('code'=>1,'msg'=>'工作列表','data'=>['total' => $total,'currentPage' => $page,'pagesNum' => $pagesNum,'rows' => $list]);
        return json($data);
    }

    /**
     * 我的员工列表
     * @ApiMethod (GET)
     */
    public function userAlreadyList()
    {
        $page =    $this->request->get('page');
        $pageSize = $this->request->get('pageSize');
        $name = $this->request->get('name');
        $tid = $this->request->get('tid'); //邀请过的就不要显示了

        $where =[];
        if(!empty($name)){
            //$where['username'] =[ 'like', '%' . $name . '%'];
            $where['realname'] =[ 'like', '%' . $name . '%'];
            //$where['nickname'] =[ 'like', '%' . $name . '%'];
        }
        //已经邀请过的
        $tids = ['tid'=>$tid];
        $yUsers  = Db::name('gongzuoshenqing')->field('uid')->where($tids)->select();
        $whereExp = [];
        if(!empty($yUsers)){
            foreach ($yUsers as $y){
                $uArray[] = $y['uid'];
            }
            $yStr = implode(",",$uArray);
            $yStr = 'NOT IN ('.$yStr.')';
            $whereExp = ['id',$yStr];
        }else{
            $data  =array('code'=>1,'msg'=>'用户列表','data'=>['total' => 0,'currentPage' => 1,'pagesNum' => 1,'rows' => []]);
            return json($data);
        }

        //$where['cId']= $this->auth->id ;//todo 员工端必须通过扫码，才能存入公司名下。
        $total = Db::name('user')->where($where)->whereExp('id',$yStr)->count();

        $pagesNum  = ceil($total/$pageSize);
        $list  = Db::name('user')->where($where)->whereExp('id',$yStr)->order(['id'=>'desc'])->limit(($page-1)*$pageSize, $pageSize)->select();
        //$thisUserObj = new User();
        if(!empty($list)){
            foreach ($list as $Item =>$value){
                //$list[$Item]['projectNums'] = $projectNums;
                //$list[$Item]['createtime'] = date('Y-m-d H:i:s',$value['createtime']);
            }
        }
        //echo  Db::name('gongzuo_project')->getLastSql();
        $data  =array('code'=>1,'msg'=>'用户列表','data'=>['total' => $total,'currentPage' => $page,'pagesNum' => $pagesNum,'rows' => $list]);
        return json($data);
    }

    /**
     * 我的团队员工列表
     * @ApiMethod (GET)
     */
    public function myUserList()
    {
        $page =    $this->request->get('page');
        $pageSize = $this->request->get('pageSize');
        $name = $this->request->get('name');
        //$tid = $this->request->get('tid'); //邀请过的就不要显示了

        $where =[];
        if(!empty($name)){
            //$where['username'] =[ 'like', '%' . $name . '%'];
            $where['realname'] =[ 'like', '%' . $name . '%'];
            //$where['nickname'] =[ 'like', '%' . $name . '%'];
        }
        //我的团队uids
        $w['cid'] = $this->auth->id;
        $yUsers  = Db::name('gongzuoshenqing')->field('uid')->where($w)->select();

        $whereExp = [];
        if(!empty($yUsers)){
            foreach ($yUsers as $y){
                $uArray[] = $y['uid'];
            }
            $yStr = implode(",",$uArray);
            $yStr = 'IN ('.$yStr.')';
            $whereExp = ['id',$yStr];
        }else{
            $data  =array('code'=>1,'msg'=>'用户列表','data'=>['total' => 0,'currentPage' => $page,'pagesNum' => 0,'rows' => []]);
            return json($data);
        }


        $total = Db::name('user')->where($where)->whereExp('id',$yStr)->count();

        $pagesNum  = ceil($total/$pageSize);
        $list  = Db::name('user')->where($where)->whereExp('id',$yStr)->order(['id'=>'desc'])->limit(($page-1)*$pageSize, $pageSize)->select();
        //$thisUserObj = new User();
        if(!empty($list)){
            foreach ($list as $Item =>$value){
                $list[$Item]['realname'] = $value['realname'];
                $list[$Item]['avatar'] = $value['avatar'];
                $list[$Item]['mobile'] = $value['mobile'];
            }
        }
        //echo  Db::name('gongzuo_project')->getLastSql();
        $data  =array('code'=>1,'msg'=>'用户列表','data'=>['total' => $total,'currentPage' => $page,'pagesNum' => $pagesNum,'rows' => $list]);
        return json($data);
    }

    /**
     * 邀请用户
     * @ApiMethod (POST)
     * @param string $tid  工作id
     *
     */
    public function yaoqing()
    {
        //如果申请过，就不能再申请
        $tid = $this->request->post('tid');  //工作id，projectId
        $usersId = $this->request->post('usersId');  //邀请的所有员工
        $beizhu = $this->request->post('beizhu');  //
    /*    if(empty($tid)){
            $yaoqingcode = $this->request->post('yaoqingcode');  //工作id
            $where = ['yaoqingcode' =>  $yaoqingcode];
            $res = Db::name('gongzuo_project')->where($where)->find();
            $tid =     $res['id'];
        }*/
        if (!$tid || !$usersId ) {
            $this->error(__('Invalid parameters'));
        }

        //检查是否申请过
/*        $whereS = [
            'uid' => $this->auth->id,
            'tid' => $tid
        ];
        $re = Db::name('gongzuoshenqing')->where($whereS)->find();
        if(!empty($re)){
            $this->error('已经申请了项目');
        }*/
        //var_dump($usersId);
        $users =  explode(',',$usersId);
         if(!empty($users)){
             foreach ($users as $u=>$value){
                 $data = [
                     'uid' => $value,
                     'cid' => $this->auth->id,
                     'tid' => $tid,
                     'beizhu' => $beizhu,
                     'addtime'=>time(),
                     'status'=>1
                 ];
                 Db::name('gongzuoshenqing')->insert($data);
             }
         }

        $this->success('邀请成功', ['action' => 'yaoqing']);
    }
    /**
     * 扫一扫
     * @ApiMethod (POST)
     * @param string $tid  工作id
     *
     */
    public function saoyisao()
    {
        $tid = $this->request->get('tid');
        if (!$tid  ) {
            $this->error(__('Invalid parameters'));
        }
        $where = ['id'=>$tid];
        $code  = Db::name('gongzuo_project')->field('yaoqingcode')->where($where)->find();
        //$url  = 'https://api.nbhao.org/v1/qrcode/make?text=https://wkfx.ruanjianbbs.net/api/faxin/applayJob?tid='.$tid.'&cid='. $this->auth->id;
        $url  = 'https://api.nbhao.org/v1/qrcode/make?text=/pages/staff/user/addProj/addProj?code='.$code['yaoqingcode'];


        $data  =array('code'=>1,'msg'=>'项目码','data'=>['code' => $code['yaoqingcode'],'url' => $url]);
        return json($data);
    }
    /**
     * 驻场请假列表
     * @ApiMethod (POST)
     */
    public function projectQingjiaList()
    {
        $page =    $this->request->get('page');
        $pageSize = $this->request->get('pageSize');
        $name = $this->request->get('name');

        //当前用户的所有项目
        $wherePro['cUid'] = $this->auth->id;
        $yUsers  = Db::name('gongzuo_project')->field('id')->where($wherePro)->select();
        $whereExp = [];
        if(!empty($yUsers)){
            foreach ($yUsers as $y){
                $uArray[] = $y['id'];
            }
            $yStr = implode(",",$uArray);
            $yStr = 'IN ('.$yStr.')';
            $whereExp = ['id',$yStr];
        }
        $where =[];
        if(!empty($name)){
            $where['name'] =[ 'like', '%' . $name . '%'];
        }
        $total = Db::name('yonghuqingjia')->where($where)->whereExp('projectid',$yStr)->count();

        $pagesNum  = ceil($total/$pageSize);
        $list  = Db::name('yonghuqingjia')->where($where)->whereExp('projectid',$yStr)->limit(($page-1)*$pageSize, $pageSize)->order('id desc')->select();
        //$typeArr  = ['1'=>'事假','2'=>'病假','3'=>'年假','4'=>'调休假','5'=>'其它'];
        if(!empty($list)){
            foreach ($list as $Item =>&$value){
                //$list[$Item]['typeS'] = $typeArr[$value['type']];
                //用户头像，realname,手机号
                $cUser  = Db::name('user')->where(['id'=>$value['uid']])->find();
                //$url  = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http";
                //$url .= "://" . $_SERVER['HTTP_HOST'];
                //$url .= $_SERVER['REQUEST_URI'];
                $list[$Item]['realname'] = empty($cUser['realname'])?'':$cUser['realname'];
                $list[$Item]['avatar'] =empty($cUser['avatar'])?'':$cUser['avatar'];
                $list[$Item]['mobile'] = empty($cUser['mobile'])?'':$cUser['mobile'];

                $proBackInfo   = Db::name('gongzuo_project')->field('projectname')->where(['id'=>$value['projectid']])->find();
                $list[$Item]['projectname'] = empty($proBackInfo['projectname'])?'':$proBackInfo['projectname'];

                $list[$Item]['startime'] = date('Y-m-d H:i:s',$value['startime']);
                $list[$Item]['endtime'] = date('Y-m-d H:i:s',$value['endtime']);
                $list[$Item]['addtime'] = date('Y-m-d H:i:s',$value['addtime']);
                if(!empty($value['files'])){
                    $list[$Item]['filesArr'] = explode(',',$value['files']);
                }
            }
        }
        $data  =array('code'=>1,'msg'=>'请假列表','data'=>['total' => $total,'currentPage' => $page,'pagesNum' => $pagesNum,'rows' => $list]);
        return json($data);
    }
    /**
 * 驻场请假审核
 * @ApiMethod (POST)
 * @param string $type
 * @param string $dizhi
 */
    public function qingjiacheck()
    {
        $id = $this->request->post('id');
        //$uid = $this->request->post('uid');
        //$projectid = $this->request->post('projectid');
        //$cUid = $this->request->post('cUid');
        $zhuangtai = $this->request->post('zhuangtai');
        $beizhu = $this->request->post('beizhu');
        if (!$id ||  !$zhuangtai) {
            $this->error(__('Invalid parameters'));
        }

        //$data['uid'] = $uid;
        //$data['projectid'] = $projectid;
        $data['cUid'] = $this->auth->id;
        $data['zhuangtai'] = $zhuangtai;
        $data['beizhu'] = $beizhu;
        //db('department_admin')->where('department_id', 'in', $childIds)->delete();
        $where = ['id' => $id];
        $res = Db::name('yonghuqingjia')->where($where)->find();
        if(empty($res)){
            $this->error('没有请假记录');
        }else{
            Db::name('yonghuqingjia')->where($where)
                ->update($data);
        }
        $this->success('批准成功', ['action' => 'qingjia']);
    }
    /**
     * 公司请假审核
     * @ApiMethod (POST)
     * @param string $type
     * @param string $dizhi
     */
    public function qingjiacheckGongsi()
    {
        $id = $this->request->post('id');
        $gongsishenhe = $this->request->post('gongsishenhe');
        $gongsishenheBhyy = $this->request->post('gongsishenheBhyy');
        if (!$gongsishenhe ) {
            $this->error(__('Invalid parameters'));
        }

        $data['gongsishenhe'] = $gongsishenhe;
        $data['gongsishenheBhyy'] = $gongsishenheBhyy;
        //db('department_admin')->where('department_id', 'in', $childIds)->delete();
        $where = ['id' => $id];
        $res = Db::name('yonghuqingjia')->where($where)->find();
        if(empty($res)){
            $this->error('没有请假记录');
        }else{
            Db::name('yonghuqingjia')->where($where)
                ->update($data);
        }
        $this->success('批准成功', ['action' => 'daka']);
    }
    /**
     * 已经发薪列表
     * @ApiMethod (Get)
     * @param string $users
     * @param string $money
     */
    public function yiFaxinList()
    {
        $page =    $this->request->get('page');
        $pageSize = $this->request->get('pageSize');
        $name = $this->request->get('name');
        $pid = $this->request->get('pid');

        $where =[];
        $yStr = '';
        if(!empty($name)){
            $where['realname'] =[ 'like', '%' . $name . '%'];
            $searchUser = Db::name('user')->field('id')->where($where)->select();

            if(!empty($searchUser)){
                foreach ($searchUser as $y){
                    $uArray[] = $y['id'];
                }
                $yStr = implode(",",$uArray);
                $yStr = 'IN ('.$yStr.')';

            }
        }
        if(!empty($name) && empty($yStr)){
            $data  =array('code'=>1,'msg'=>'发薪用户列表','data'=>['total' => 0,'currentPage' => $page,'pagesNum' => 0,'rows' => []]);
            return json($data);
        }
        //已经邀请过的
        $wherePid = ['pid'=>$pid];
        $total = Db::name('yonghugongzidan')->where($wherePid)->whereExp('uid',$yStr)->count();


        $pagesNum  = ceil($total/$pageSize);
        $list  = Db::name('yonghugongzidan')->where($wherePid)->whereExp('uid',$yStr)->order(['id'=>'desc'])->limit(($page-1)*$pageSize, $pageSize)->select();

        //$thisUserObj = new User();
        if(!empty($list)){
            foreach ($list as $Item =>$value){
                $cUser  = Db::name('user')->where(['id'=>$value['uid']])->find();
                $list[$Item]['realname'] = empty($cUser['realname'])?'':$cUser['realname'];
                $list[$Item]['avatar'] =empty($cUser['avatar'])?'':$cUser['avatar'];
                $list[$Item]['mobile'] = empty($cUser['mobile'])?'':$cUser['mobile'];
            }
        }
        //echo  Db::name('gongzuo_project')->getLastSql();
        $data  =array('code'=>1,'msg'=>'发薪用户列表','data'=>['total' => $total,'currentPage' => $page,'pagesNum' => $pagesNum,'rows' => $list]);
        return json($data);
    }

    /**
     * 未发薪列表
     * @ApiMethod (Get)
     * @param string $users
     * @param string $money
     */
    public function weiFaxinList()
    {
        $page =    $this->request->get('page');
        $pageSize = $this->request->get('pageSize');
        $name = $this->request->get('name');
        $pid = $this->request->get('pid');

        $where =[];
        $yStr = '';

        $where['pid'] =$pid;
        //$where['money'] =$pid;
        $searchUser = Db::name('yonghugongzidan')->field('uid')->where($where)->select();

        if(!empty($searchUser)){
            foreach ($searchUser as $y){
                $uArray[] = $y['uid'];
            }
            $yStr = implode(",",$uArray);
            $yStr = 'NOT IN ('.$yStr.')';
        }

        $whereU = ['cId'=>$this->auth->id];
        if(!empty($name)) {
            $whereU['realname'] = ['like', '%' . $name . '%'];
            $whereU['cId'] = $this->auth->id;
        }
        $total = Db::name('user')->where($whereU)->whereExp('id',$yStr)->count();

        $pagesNum  = ceil($total/$pageSize);
        $list  = Db::name('user')->where($whereU)->whereExp('id',$yStr)->order(['id'=>'desc'])->limit(($page-1)*$pageSize, $pageSize)->select();

        //$thisUserObj = new User();
        $total  =0;
        if(!empty($list)){
            foreach ($list as $Item =>$value){
                $cUser  = Db::name('user')->where(['id'=>$value['uid']])->find();
                $list[$Item]['realname'] = empty($cUser['realname'])?'':$cUser['realname'];
                $list[$Item]['avatar'] =empty($cUser['avatar'])?'':$cUser['avatar'];
                $list[$Item]['mobile'] = empty($cUser['mobile'])?'':$cUser['mobile'];
            }
        }
        //echo  Db::name('gongzuo_project')->getLastSql();
        $data  =array('code'=>1,'msg'=>'未发薪用户列表','data'=>['total' => $total,'currentPage' => $page,'pagesNum' => $pagesNum,'rows' => $list]);
        return json($data);
    }

    /**
     * 发薪总额
     * @ApiMethod (Get)
     * @param string $users
     * @param string $money
     */
    public function faxinTotal()
    {
        $pid = $this->request->get('pid');
        if (!$pid) {
            $this->error(__('Invalid parameters'));
        }
        $where['pid'] =$pid;
        $total = Db::name('yonghufaxintotal')->where($where)->sum('money');
        $row['totalmoney']=$total;
        //已发薪人数
        $ynums = Db::name('yonghufaxintotal')->where($where)->count();
        $row['yifaxinNums']=$ynums;
        //未发薪人数
        $whereR['cId'] =$this->auth->id;
        $wnums = Db::name('user')->where($whereR)->count();
        $row['weifaxinNums']=$wnums-$ynums;
        $data  =array('code'=>1,'msg'=>'发薪总额','data'=>$row);
        return json($data);
    }
    /**
 * 发薪
 * @ApiMethod (POST)
 * @param string $users  4,5,7,8
 * @param string $pid
 */
    public function faxin()
    {

        $pid = $this->request->post('pid'); //pid
        $projectname = $this->request->post('projectname'); //pid
        $usersId = $this->request->post('usersId'); //pid
        $money = $this->request->post('money'); //pid
        $yArray = [];

        if(!empty($usersId)){
            $yArray = explode(",",$usersId);
        }

        if(!empty($yArray)){
            foreach($yArray as $item ){
                //$data['batch_id'] = $resData['batch_id'];
                //$data['out_batch_no'] = $uValue['out_detail_no'];
                $data['uid'] = $item;
                $data['pid'] = $pid;
                $data['projectname'] = $projectname;
                $data['cUid'] = $this->auth->id;
                $data['money'] = $money;
                $data['addtime'] = time();
                $data['zhangqi'] = date('Y-m',time());//以月为账期？
                $dataItem = $data;
                $data['updatetime'] = time();
                //平时打卡记录 加入到 工资单
                $Gwhere['uid'] = $data['uid'];
                $Gwhere['pid'] = $pid;
                $Gwhere['zhangqi'] = date('Y-m',time());
                $gRes  =  Db::name('yonghuday_chidao')->where($Gwhere)->find();
                if(!empty($gRes)){
                    $dataItem['chidaoCishu'] = $gRes['chidaoCishu'];
                    $dataItem['chidaobeizhu'] = $gRes['chidaobeizhu'];
                    $dataItem['shijiDakaDays'] = $gRes['dakaCishu'];
                }
                Db::name('yonghugongzidan')->insert($dataItem);
                //把提现时的压薪时间加到用户余额信息里
                $yaxinRes = Db::name('gongzuo_project')->field('yaxin')->where(['id'=>$pid])->find();
                if($yaxinRes['yaxin'] && (int)$yaxinRes['yaxin']>0){
                    $yaxinShijiandian = time()+(int)$yaxinRes['yaxin']*24*60*60;
                }else{
                    $yaxinShijiandian =0;
                }
                $sql  =  'UPDATE fa_user set money = money +'.$money.',zongshouru = zongshouru+'.$money.' ,yaxinShijiandian = '.$yaxinShijiandian.' WHERE id = '.$data['uid'];

                Db::query($sql);
//                $whereUser = ['uid'=>$item];
//                $tem = Db::name('yonghufaxintotal')->field('money')->where($whereUser)->find();
//
//                if(!empty($tem)){
//                    $newMoney  = (int)$tem['money']+$money;
//                    Db::name('yonghufaxintotal')->where(['uid'=>$item])->update(['money'=>$newMoney]);
//                }else{
//                    Db::name('yonghufaxintotal')->insert($data);
//                }
            }
        }
        $databack  =array('code'=>1,'msg'=>'发薪成功','data'=>true);
        return json($databack);
    }
    /**
     * 提现
     * @ApiMethod (POST)
     * @param string $type
     * @param string $dizhi
     */
    public function tixian()
    {

        //to do 2023-10-30 改接收uids为接收openId
        //$openId = $this->request->post('openId'); //前端获得：https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-login/code2Session.html
        $uid = $this->request->post('uid');
        $cUid = $this->request->post('cUid');
        $money = $this->request->post('money');
        $pid = $this->request->post('pid');
        $projectname = $this->request->post('projectname');
        //$money = $this->request->post('money');

        if (!$uid || !$pid|| !$money) {
            $res  =array('code'=>0,'msg'=>'参数不对');
            return json($res);
        }

        //判断是否压薪
        $yaxinRes = Db::name('user')->field('yaxinShijiandian')->where(['id'=>$uid])->find();

        if($yaxinRes['yaxinShijiandian'] && (int)$yaxinRes['yaxinShijiandian']>time()){
                $res  =array('code'=>0,'msg'=>'发钱用户不能为空');
                return json($res);
        }
        /*$uidArr  = json_decode($uids);
        if(empty($uidArr->users)){
            if(empty($uidArr->users)){
            $res  =array('code'=>0,'msg'=>'发钱用户不能为空');
            return json($res);
        }
        }*/

        $data['uid'] = $uid;
        $data['pid'] = $pid;
        $data['projectname'] = $projectname;
        $data['addtime'] = time();
        //商户信息
        $huInfo['app_id'] ='wxa5d500b7717dc5e5';
        $huInfo['mchid']='1657226654';//商户id
        $huInfo['cert_pem']='cert';//设置文件标志
        $huInfo['key_pem']='key';

        $wechatPayObject = new  WechatPayTransfer($huInfo);
        //Db::startTrans();

        $data['cUid'] = $cUid; //发钱者id
        $data['zhangqi'] = date('Y-m',time());//以月为账期？
        //调用微信支付红包
        //$batch_name, $batch_remark, $out_trade_no, $money, $openid
        $batch_name='工资';
        $tradeString ='ds'.time().str_pad(mt_rand(0, 999999), 6, "0", STR_PAD_BOTH);
        $out_trade_no = "batch".$tradeString;
        $batch_remark = date('Y-m-d').'备注';
        $totalMoney = 0;
        $user = array();
        $users = array();
        //foreach ($uidArr->users as $item) {
            $user['out_detail_no'] = "transfer".$tradeString;
            $user['transfer_amount'] = $money*100;
            $user['transfer_remark'] = $batch_name;
            $userInfo = Db::name('user')->field('openId')->where(['id'=>$uid])->find();
            $user['openid'] = $userInfo['openId'];
            $totalMoney +=  $money*100;
            $users[] = $user;
        //}
        //调用微信支付红包
        //$batch_name, $batch_remark, $out_trade_no, $money, $openid
        //var_dump($batch_name, $batch_remark, $users, $totalMoney);
        $resData = $wechatPayObject->transfer($batch_name, $out_trade_no,$batch_remark, $users, $totalMoney);

        if(isset($resData['batch_id']) && $resData['batch_id']){
            foreach ($users as $uItem=>$uValue){
                $data['batch_id'] = $resData['batch_id'];
                $data['out_batch_no'] = $uValue['out_detail_no'];
                $data['money'] = $uValue['transfer_amount']/100;//$uValue['transfer_amount']/100;
                $data['beizhu'] = $batch_name;
                Db::name('yonghufaxin')->insert($data);
                //更改用户余额


                $sql  =  'UPDATE fa_user set money = money -'.$data['money'].',yiti = yiti+'.$data['money'].' WHERE id = '.$data['uid'];
                Db::query($sql);

            }
            $this->success('发钱成功', ['action' => 'faxin']);
        }else{
            $this->result('发钱失败', ['code' => 0]);
        }

        $data  =array('code'=>0,'msg'=>'未知错误');
        return json($data);
    }
    /**
     * 项目账单列表
     * @ApiMethod (Get)
     * @param string $users
     * @param string $money
     */
    public function projectZhangdanList()
    {
        $page =    $this->request->get('page');
        $pageSize = $this->request->get('pageSize');
        $faxintype = $this->request->get('faxintype');
        $pName = $this->request->get('pName');

        $where = ['cUid' => $this->auth->id ];
        if(!empty($faxintype)){
            $where['faxintype'] = $faxintype;
        }
        if(!empty($pName)){
            $where['projectname'] =[ 'like', '%' . $pName . '%'];
        }


        $total = Db::name('gongzuo_project')->where($where)->count();

        $pagesNum  = ceil($total/$pageSize);
        $list  = Db::name('gongzuo_project')->where($where)->order(['id'=>'desc'])->limit(($page-1)*$pageSize, $pageSize)->select();

        //$thisUserObj = new User();
        if(!empty($list)){
            foreach ($list as $Item =>$value){
                /*                $cUser  = Db::name('user')->where(['id'=>$value['cUid']])->find();
                                $list[$Item]['fubuzheTouxiang'] =$cUser['avatar'];
                                $list[$Item]['fubuzheMobile'] = $cUser['mobile'];*/
                //账期发放金额 ，暂时按月为账期
                $whereM['pid']=$value['id'];
                //$whereM['zhangqi'] = date('Y-m',time());
                $totalMoney =  Db::name('yonghugongzidan')->where($whereM)->sum('money');
                $list[$Item]['totalMoney'] = $totalMoney;

                //统计这个项目的人数
                $projectNums = Db::name('gongzuoshenqing')->where(['tid'=>$value['id']])->count();
                $list[$Item]['projectNums'] = $projectNums;
                $list[$Item]['createtime'] = date('Y-m-d H:i:s',$value['createtime']);

            }
        }
        //echo  Db::name('gongzuo_project')->getLastSql();
        $data  =array('code'=>1,'msg'=>'项目列表','data'=>['total' => $total,'currentPage' => $page,'pagesNum' => $pagesNum,'rows' => $list]);
        return json($data);
    }
    /**
     * 账单列表(详情)
     * @ApiMethod (Get)
     * @param string $users
     * @param string $money
     */
    public function zhangdanList()
    {
        $page =    $this->request->get('page');
        $pageSize = $this->request->get('pageSize');
        $pid = $this->request->get('pid');
        $uName = $this->request->get('uName');
        if(!empty($uName)){
            $yStr ='999';
            $where['realname'] =[ 'like', '%' . $uName . '%'];
            $yUsers  = Db::name('user')->field('id')->where($where)->select();
            if(!empty($yUsers)){
                foreach ($yUsers as $y){
                    $uArray[] = $y['id'];
                }
                $yStr = implode(",",$uArray);
                $yStr = 'IN ('.$yStr.')';
                $whereExp = ['id',$yStr];
            }

            $wherePid = ['pid'=>$pid];
            $total = Db::name('yonghugongzidan')->where($wherePid)->whereExp('uid',$yStr)->count();

            $pagesNum  = ceil($total/$pageSize);
            $list  = Db::name('yonghugongzidan')->where($wherePid)->whereExp('uid',$yStr)->order(['id'=>'desc'])->limit(($page-1)*$pageSize, $pageSize)->select();
        }else{
            $wherePid = ['pid'=>$pid];
            $total = Db::name('yonghugongzidan')->where($wherePid)->count();
            $pagesNum  = ceil($total/$pageSize);
            $list  = Db::name('yonghugongzidan')->where($wherePid)->order(['id'=>'desc'])->limit(($page-1)*$pageSize, $pageSize)->select();
        }



        //$thisUserObj = new User();
        if(!empty($list)){
            foreach ($list as $Item =>$value){
                $cUser  = Db::name('user')->where(['id'=>$value['uid']])->find();
                $list[$Item]['realname'] = empty($cUser['realname'])?'':$cUser['realname'];
                $list[$Item]['avatar'] =empty($cUser['avatar'])?'':$cUser['avatar'];
                $list[$Item]['mobile'] = empty($cUser['mobile'])?'':$cUser['mobile'];
            }
        }

        $data  =array('code'=>1,'msg'=>'发薪账单列表','data'=>['total' => $total,'currentPage' => $page,'pagesNum' => $pagesNum,'rows' => $list]);
        return json($data);
    }

    /**
     * 账单列表(详情)-单个人
     * @ApiMethod (Get)
     * @param string $users
     * @param string $money
     */
    public function zhangdanListUser()
    {
        $page =    $this->request->get('page');
        $pageSize = $this->request->get('pageSize');
        $pid = $this->request->get('pid');
        $uid = $this->request->get('uid');

        //已经邀请过的
        $wherePid['pid']=$pid;
        $wherePid['uid']=$pid;
        $total = Db::name('yonghugongzidan')->where($wherePid)->count();


        $pagesNum  = ceil($total/$pageSize);
        $list  = Db::name('yonghugongzidan')->where($wherePid)->order(['id'=>'desc'])->limit(($page-1)*$pageSize, $pageSize)->select();

        //$thisUserObj = new User();
        if(!empty($list)){
            foreach ($list as $Item =>$value){
                $cUser  = Db::name('user')->where(['id'=>$value['uid']])->find();
                $list[$Item]['realname'] = empty($cUser['realname'])?'':$cUser['realname'];
                $list[$Item]['avatar'] =empty($cUser['avatar'])?'':$cUser['avatar'];
                $list[$Item]['mobile'] = empty($cUser['mobile'])?'':$cUser['mobile'];
            }
        }

        $data  =array('code'=>1,'msg'=>'详情','data'=>['total' => $total,'currentPage' => $page,'pagesNum' => $pagesNum,'rows' => $list]);
        return json($data);
    }
    /**
     * 驻场反饋列表
     * @ApiMethod (GET)
     */
    public function anwserList()
    {
        $page =    $this->request->get('page');
        $pageSize = $this->request->get('pageSize');
        $type = $this->request->get('type');
        $whereU = ['cid'=>$this->auth->id];
        if(!empty($type)){
            $whereU['type'] = $type;
        }
        $total = Db::name('gongzuofankui')->where($whereU)->count();
        $pagesNum  = ceil($total/$pageSize);
        $list  = Db::name('gongzuofankui')->where($whereU)->limit(($page-1)*$pageSize, $pageSize)->order('id desc')->select();
        //$thisUserObj = new User();
        $blist = array();
        if(!empty($list)){
            foreach ($list as $Item =>&$value){
                if(!empty($value['files'])){
                    $cUser  = Db::name('user')->where(['id'=>$value['uid']])->find();
                    $list[$Item]['fankuiname'] = empty($cUser['realname'])?'':$cUser['realname'];
                    //$url  = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http";
                    //$url .= "://" . $_SERVER['HTTP_HOST'].$value['files'];
                    $list[$Item]['fullpath'] = $value['files'];
                    //echo $value['create_time'];
                    $list[$Item]['answerTime'] = date('Y-m-d H:i:s',$value['answerTime']);
                    $list[$Item]['createtime'] = date('Y-m-d H:i:s',$value['createtime']);
                }
                $blist[]  =  $list[$Item];
            }
        }
        //echo  Db::name('gongzuo_project')->getLastSql();
        $data  =array('code'=>1,'msg'=>'工作列表','data'=>['total' => $total,'currentPage' => $page,'pagesNum' => $pagesNum,'rows' => $blist]);
        return json($data);
    }

    /**
     * 问题反馈
     * @ApiMethod (POST)
     * @param string $answer
     *
     */
    public function askAnswer()
    {
        $id = $this->request->post('id');
        $answer = $this->request->post('answer');
        if (!$id || !$answer) {
            $this->error(__('Invalid parameters'));
        }
        $data = [
            'cid' => $this->auth->id,
            'answer' => $answer,
            'answerTime'=>time()
        ];
        Db::name('gongzuofankui')->where(['id'=>$id])->update($data);

        $this->success('反馈成功', ['action' => 'askAnswer']);
    }

}
